(ns xuan-clj.service.token
  (:require [clj-time.core :refer :all]
            [clj-jwt.core :as jwt]))

(defn- create-claim [username]
  {:iss      "xuan"
   :exp      (plus (now) (days 1))
   :iat      (now)
   :username username
   })

(defn create-token [username]
  (-> username create-claim jwt/jwt (jwt/sign :HS256 "xuan-secret") jwt/to-str))

(defn decode-token [token]
  (-> token jwt/str->jwt :claims :username))

(defn token-expires? [token]
  (-> token jwt/str->jwt :claims :exp (* 1000) (< (.getMillis (now))))
  )

(defn- try-verify-token [jwt-token]
  (try (jwt/verify jwt-token :HS256 "xuan-secret")
       (catch Exception _ false))
  )

(defn- try-str->jwt [token]
  (try (jwt/str->jwt token)
       (catch Exception _ nil))
  )

(defn verify-token [token]
  (-> token try-str->jwt try-verify-token))